package StudyCode.summary.zipfile;

import java.io.*;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;

/**
 * 版权所有 科技与人文(www.tah1986.com)
 */
public class DecompressZipFileDirectoryOptionAllDeletingZipFile {
	private static int BUFFER_SIZE = 2048;

	public static void decompressZip(String zipFile, String destDir,
	                                 boolean deleteZip) throws RuntimeException {
		if (!destDir.endsWith("/"))
			destDir = destDir.concat("/");

		try {
			BufferedOutputStream bos = null;
			FileInputStream fis = new FileInputStream(zipFile);
			ZipInputStream zis = new ZipInputStream(
					new BufferedInputStream(fis));
			ZipEntry zipEntry;

			while ((zipEntry = zis.getNextEntry()) != null) {
				String zipEntryName = zipEntry.getName();
				File file = new File(destDir + zipEntryName);

				if (file.exists()) {

				} else {
					if (zipEntry.isDirectory()) {
						file.mkdirs();
					} else {

						byte data[] = new byte[BUFFER_SIZE];
						FileOutputStream fos = new FileOutputStream(file);
						bos = new BufferedOutputStream(fos, BUFFER_SIZE);
						int count;

						while ((count = zis.read(data, 0, BUFFER_SIZE)) != -1) {
							bos.write(data, 0, count);
						}

						bos.flush();
						bos.close();
					}
				}
			}
			zis.close();
		} catch (FileNotFoundException ffe) {
			throw new RuntimeException(ffe);
		} catch (IOException ioe) {
			throw new RuntimeException(ioe);
		}

		if (deleteZip) {
			File zip = new File(zipFile);
			if (zip.exists()) {
				zip.delete();
			}
		}
	}
}
